from rest_framework import serializers
from auditlog.models import *


class LogEntrySerializer(serializers.ModelSerializer):
    user = serializers.CharField(source='object_repr')
    action = serializers.SerializerMethodField()
    timestamp = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S')
    actor = serializers.StringRelatedField()
    content_type = serializers.StringRelatedField()
    changes = serializers.SerializerMethodField()
    # name_model = serializers.CharField(source='contenttypes.ContentType.model')
    # object_pk = serializers.ChoiceField(source='object_repr', (('1', "username"),
    #             ('2', "last_login_time"),
    #             ('3', "create_time"),
    #             ('4', "删除"), ('5', "删除")))

    class Meta:
        model = LogEntry
        exclude = ('id', 'object_repr', 'object_id', 'object_pk')

    def get_action(self, obj):
        return obj.get_action_display()

    def get_changes(self, obj):
        query_set = json.loads(obj.changes)
        if 'date_joined' in list(query_set.keys()) or 'create_time' in list(query_set.keys()) \
                or 'last_login' in list(query_set.keys()):
            return [{'change_attr': key, 'change_before': value[0][:19], 'change_after': value[1][:19]}
                        for key, value in query_set.items()]
        else:
            return [{'change_attr': key, 'change_before': value[0], 'change_after': value[1]}
                            for key, value in query_set.items()]


class RequestEventSerializer(serializers.ModelSerializer):
    time = serializers.DateTimeField(source='datetime', format='%Y-%m-%d %H:%M:%S')
    # user = serializers.CharField(source='user.username')
    user = serializers.StringRelatedField()
    # url = serializers.HyperlinkedIdentityField(view_name='User-login_username')
    # url = serializers.HyperlinkedRelatedField(view_name='user:login_username', many=False,
    #                                           read_only=True)

    class Meta:
        model = RequestEvent
        exclude = ('id', 'datetime')


class LoginEventSerializer(serializers.ModelSerializer):
    action = serializers.SerializerMethodField()
    action_time = serializers.DateTimeField(source='created', format='%Y-%m-%d %H:%M:%S')
    user = serializers.StringRelatedField()

    class Meta:
        model = LoginEvent
        fields = ['action', 'username', 'remote_ip', 'action_time', 'user']

    def get_action(self, obj):
        return obj.get_action_display()
